package com.zry.fertilizer.utils

import android.app.Activity
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo

/**
 * Created by zry on 2017/12/5.
 */

class NetWorkUtils {
    fun isNetworkAvailable(activity: Activity): Boolean {
        val context: Context = activity.applicationContext
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (connectivityManager == null) {
            return false
        } else {
            // 获取NetworkInfo对象
            val networkInfo = connectivityManager.allNetworkInfo
            if (networkInfo != null && networkInfo.isNotEmpty()) {
                networkInfo.indices
                        .filter {
                            // 判断当前网络状态是否为连接状态
                            networkInfo[it].state == NetworkInfo.State.CONNECTED
                        }
                        .forEach { return true }
            }
        }
        return false
    }
}
